//
//  KFDMarketViewController.m
//  KFD
//
//  Created by JIRENTIANXIANG on 6/9/15.
//  Copyright (c) 2015 kfd. All rights reserved.
//

#import "KFDMarketViewController.h"
#import "KFDPriceBoard.h"
#import "KFDMarketViewModel.h"
#import "ui_config.h"
#import "KFDMarketInfoContainer.h"
#import "JRTXDiagramView.h"
#import "KFDDiagramPoint.h"
#import "KFDAnnouncementListViewController.h"
#import "NSDate+format.h"
#import "KFDDetailedDiagramViewController.h"
#import <Reachability/Reachability.h>
#import "client_config.h"
#import "NSDate+range.h"
#import "KFDChatListViewController.h"

#define KFDMarketInfoContainerTopHigh (130+15+139+20)*0.5
#define KFDMarketInfoContainerTopLow (130+15+139+242+20)*0.5

#define X_INDEX_COUNT 6
#define Y_INDEX_COUNT 4

@interface KFDMarketViewController ()<JRTXDiagramDataSource>

@property (strong,nonatomic) KFDMarketViewModel* viewModel;
@property (strong,nonatomic) UIScrollView* priceBoardContainer;
@property (strong,nonatomic) NSArray* priceBoards;
@property (strong,nonatomic) KFDMarketInfoContainer* marketInfoContainer;

@end

@implementation KFDMarketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureNavigationBar];
    [self configureViewModel];
    [self setupDiagramView];
    [self setupPriceBoardContainer];
    [self setupPriceBoards];
    [self configureMarketInfoContainer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDiagramView) name:KFDMarketDiagramViewShouldUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePriceBoards) name:KFDMarketPricesReadyNotification object:nil];
    [self.viewModel loadMarketPrices];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KFDMarketDiagramViewShouldUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KFDMarketPricesReadyNotification object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.viewModel startMarketPriceTimer];
    [self.viewModel startDiagramTimer];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.viewModel stopMarketPriceTimer];
    [self.viewModel stopDiagramTimer];
}

-(void)setupPriceBoards
{
    int count=14;
    CGFloat height=69.5;
    NSMutableArray* priceBoards=[NSMutableArray array];
    self.priceBoardContainer.contentSize=CGSizeMake(SCREEN_WIDTH*count/3, 0);
    for (int i=0;i<count;i++) {
        KFDPriceBoard* priceBoard=[[KFDPriceBoard alloc] initWithFrame:CGRectMake(((SCREEN_WIDTH-1)/3+0.5)*i, 0, (SCREEN_WIDTH-1)/3, height)];
        priceBoard.tag=i;
        priceBoard.backgroundColor=[UIColor whiteColor];
        [priceBoard addTarget:self action:@selector(priceBoardPressed:) forControlEvents:UIControlEventTouchUpInside];
        [priceBoards addObject:priceBoard];
        [self.priceBoardContainer addSubview:priceBoard];
    }
    KFDPriceBoard* board0=priceBoards.firstObject;
    board0.selected=YES;
    self.viewModel.currentPriceIndex=0;
    self.priceBoards=priceBoards;
}

-(void)configureNavigationBar
{
    //configure title view
    UIView* titleView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    UILabel* kfdLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    kfdLabel.text=@"凯福德金业";
    kfdLabel.textColor=[UIColor whiteColor];
    kfdLabel.font=[UIFont systemFontOfSize:16];
    kfdLabel.textAlignment=NSTextAlignmentCenter;
    [titleView addSubview:kfdLabel];
    UILabel* urlLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 10)];
    urlLabel.text=@"www.kfd9999.com";
    urlLabel.textAlignment=NSTextAlignmentCenter;
    urlLabel.textColor=[UIColor whiteColor];
    urlLabel.font=[UIFont systemFontOfSize:9];
    [titleView addSubview:urlLabel];
    self.navigationItem.titleView=titleView;
    
    //configure left bar button item
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"header-notice-ico"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonPressed)];
    
    //configure right bar button item
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"header-msg-ico"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonPressed)];
}

-(void)configureViewModel
{
    self.viewModel=[KFDMarketViewModel new];
//    [self.viewModel registerObserver:self];
}

-(void)setupPriceBoardContainer
{
    CGFloat top=72.5;
    CGFloat height=69.5;
    self.priceBoardContainer=[[UIScrollView alloc] initWithFrame:CGRectMake(0, top, SCREEN_WIDTH, height)];
    self.priceBoardContainer.contentInset=UIEdgeInsetsZero;
    self.priceBoardContainer.contentOffset=CGPointMake(0, 0);
    self.priceBoardContainer.showsHorizontalScrollIndicator=NO;
    self.priceBoardContainer.showsVerticalScrollIndicator=NO;
    self.priceBoardContainer.pagingEnabled=YES;
    self.priceBoardContainer.backgroundColor=KFDColorRGB(0xb3, 0xb3, 0xb3);
    [self.view addSubview:self.priceBoardContainer];
}

-(void)setupDiagramView
{
    JRTXDiagramViewConfiguration* config=[[JRTXDiagramViewConfiguration alloc] init];
    config.leftPadding=30;
    config.rightPaddig=20;
    config.topPadding=10;
    config.bottomPadding=20;
    config.verticalScale=0.8;
    config.lineWidth=2;
    config.lineColor=[UIColor colorWithRed:0.2 green:0.4 blue:0.4 alpha:1];
    config.shadowColor=[UIColor colorWithRed:0.6 green:0.9 blue:0.9 alpha:1];
    self.diagramView=[[JRTXDiagramView alloc] initWithFrame:CGRectMake(0, KFDMarketInfoContainerTopHigh-20*0.5, SCREEN_WIDTH, KFDMarketInfoContainerTopLow-KFDMarketInfoContainerTopHigh) configuration:config];
    self.diagramView.backgroundColor=[UIColor whiteColor];
    self.diagramView.dataSource=self;
    [self.view addSubview:self.diagramView];
    UITapGestureRecognizer* recognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(diagramViewTapped)];

    [self.diagramView addGestureRecognizer:recognizer];
}

-(void)diagramViewTapped
{
    if (self.viewModel.marketPrices.count==0) {
        return;
    }
    KFDDetailedDiagramViewController* detailedDiagramVC=[[KFDDetailedDiagramViewController alloc] init];
    detailedDiagramVC.viewModel.marketPrices=self.viewModel.marketPrices;
    detailedDiagramVC.viewModel.currentPriceIndex=self.viewModel.currentPriceIndex;
    [self.navigationController pushViewController:detailedDiagramVC animated:YES];
}

-(void)configureMarketInfoContainer
{
    _marketInfoContainer=[[KFDMarketInfoContainer alloc] initWithTableViewFrameLow:CGRectMake(0, KFDMarketInfoContainerTopLow, SCREEN_WIDTH, SCREEN_HEIGHT-KFDMarketInfoContainerTopLow-50) tableViewFrameHigh:CGRectMake(0, KFDMarketInfoContainerTopHigh, SCREEN_WIDTH, SCREEN_HEIGHT-KFDMarketInfoContainerTopHigh-50) diagramViewFrame:CGRectMake(0, KFDMarketInfoContainerTopHigh-20*0.5, SCREEN_WIDTH, KFDMarketInfoContainerTopLow-KFDMarketInfoContainerTopHigh) viewController:self];
    [self.view addSubview:_marketInfoContainer];
}

-(void)priceBoardPressed:(KFDPriceBoard*)sender
{
    for (KFDPriceBoard* priceBoard in self.priceBoards) {
        if (priceBoard==sender) {
            priceBoard.selected=YES;
//            self.selectedType=sender.price.typename;
            self.viewModel.currentPriceIndex=sender.tag;
            [self.viewModel loadDiagramPoints];
//            self.viewModel.currentPriceIndex=sender.tag;
            
        }else{
            priceBoard.selected=NO;
        }
    }
}

-(void)updatePriceBoards
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSArray* prices=self.viewModel.marketPrices;
        for (int i=0; i<prices.count; i++) {
            KFDPriceBoard* priceBoard=self.priceBoards[i];
            priceBoard.price=prices[i];
        }
    });
}

-(void)updateDiagramView
{
    NSMutableArray* diagramData=[NSMutableArray array];
    NSArray* diagramPoints=self.viewModel.diagramPointsOfAllTypes[self.viewModel.currentPriceIndex];
    for (KFDDiagramPoint* diagramPoint in diagramPoints) {
        NSDate* date=diagramPoint.date;
        NSTimeInterval time=date.timeIntervalSince1970;
        JRTXDiagramDatum* diagramDatum=[JRTXDiagramDatum diagramDatumWithX:@(time) andY:diagramPoint.price];
        [diagramData addObject:diagramDatum];
    }
    self.diagramView.diagramData=diagramData;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.diagramView updateDisplay];
    });
}

-(void)leftBarButtonPressed
{
    KFDAnnouncementListViewController* announcementListVC=[[KFDAnnouncementListViewController alloc] init];
    [self.navigationController pushViewController:announcementListVC animated:YES];
}
-(void)rightBarButtonPressed
{
    KFDChatListViewController* vc=[[KFDChatListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
//    UIAlertController* alertController=[UIAlertController alertControllerWithTitle:nil message:@"没有检测到MT4交易软件，是否需要下载安装？" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction* cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
//    [alertController addAction:cancel];
//    UIAlertAction* ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
//    [alertController addAction:ok];
//    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//-----------------------------------------------------------------------
#pragma mark - JRTXDiagramViewDataSource
//-----------------------------------------------------------------------
-(NSInteger)numberOfXIndicesInDiagramView:(JRTXDiagramView *)diagramView
{
    return X_INDEX_COUNT;
}
-(NSNumber*)diagramView:(JRTXDiagramView *)diagramView valueForXIndex:(NSInteger)index
{
    JRTXDiagramDataDisplayMapper* mapper=self.diagramView.mapper;
    return @(mapper.minX+index*mapper.xSpan/(X_INDEX_COUNT-1));
}
-(UIView*)diagramView:(JRTXDiagramView *)diagramView viewForXIndex:(NSInteger)index
{
    UILabel* label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 10)];
    label.textColor=KFD_TEXT_DARK_GRAY;
    label.font=[UIFont systemFontOfSize:5];
    JRTXDiagramDataDisplayMapper* mapper=self.diagramView.mapper;
    float time=mapper.minX+index*mapper.xSpan/(X_INDEX_COUNT-1);
    if (self.viewModel.currentPriceIndex==0&&time>self.viewModel.breakPointTime) {
        time+=self.viewModel.breakInterval;
    }
    NSDate* date=[NSDate dateWithTimeIntervalSince1970:time];
    label.text=[NSString stringWithFormat:@"%@ %@",date.month_day,date.hour_minute];
    return label;
}
-(NSInteger)numberOfYIndicesInDiagramView:(JRTXDiagramView *)diagramView
{
    return Y_INDEX_COUNT;
}
-(NSNumber*)diagramView:(JRTXDiagramView *)diagramView valueForYIndex:(NSInteger)index
{
    JRTXDiagramDataDisplayMapper* mapper=self.diagramView.mapper;
    return @(mapper.minY+index*mapper.ySpan/(Y_INDEX_COUNT-1));
}
-(UIView*)diagramView:(JRTXDiagramView *)diagramView viewForYIndex:(NSInteger)index
{
    UILabel* label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 4)];
    label.textColor=KFD_TEXT_DARK_GRAY;
    label.font=[UIFont systemFontOfSize:5];
    JRTXDiagramDataDisplayMapper* mapper=self.diagramView.mapper;
    NSNumber* value=@(mapper.minY+index*mapper.ySpan/(Y_INDEX_COUNT));
    label.text=[NSString stringWithFormat:@"%.2f",value.floatValue];
    return label;
}
-(JRTXDiagramViewLineStyle*)diagramView:(JRTXDiagramView *)diagramView lineStyleForYIndex:(NSInteger)index
{
    JRTXDiagramViewLineStyle* lineStyle=[JRTXDiagramViewLineStyle lineStyleWithColor:[UIColor lightGrayColor] lineWidth:1 segmentLength:2 gapLength:1];
    return lineStyle;
}

//-----------------------------------------------------------------------

@end
